import styles from './SearchPage.module.css'
import React, { useEffect } from 'react'
import { Header, Footer, FilterArea, ProductList } from '../../components'
import { useParams, useLocation } from 'react-router-dom'
import { Spin } from 'antd'
import { searchProduct } from '../../redux/productSearch/slice'
import { useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'

interface MatchParams {
  keywords?: string
}
export const SearchPage: React.FC<MatchParams> = () => {
  const { keywords } = useParams()

  const loading = useSelector((state: any) => state.productSearch?.loading)
  const error = useSelector((s: any) => s.productSearch?.error)
  const pagination = useSelector((s: any) => s.productSearch?.pagination)
  const productList = useSelector((s: any) => s.productSearch?.data)

  const dispatch = useDispatch()
  const location = useLocation()

  useEffect(() => {
    dispatch(
      searchProduct({
        nextPage: 2,
        pageSize: 2,
        keywords: keywords ?? '',
      }) as any
    )
  }, [location])

  const onPageChange = (nextPage: any, pageSize: any) => {
    dispatch(
      searchProduct({ nextPage, pageSize, keywords: keywords ?? '' }) as any
    )
  }

  if (loading) {
    return (
      <Spin
        size="large"
        style={{
          marginTop: 200,
          marginBottom: 200,
          marginLeft: 'auto',
          marginRight: 'auto',
          width: '100%',
        }}
      />
    )
  }
  if (error) {
    return <div>网站出错：{error}</div>
  }

  return (
    <>
      <Header />
      <div className={styles['page-content']}>
        {/* 分类 */}
        <div className={styles['product-list-container']}></div>
        <FilterArea />
        {/* 产品列表 */}
        <div className={styles['product-list-container']}>
          <ProductList
            data={productList}
            paging={pagination}
            onPageChange={onPageChange}
          />
        </div>
      </div>
    </>
  )
}
